import Taro from '@tarojs/taro';
import React, { useState, useEffect } from 'react';
import { View, Text, ScrollView, TouchableOpacity, Image } from '@tarojs/components';
import { MaterialIcons } from 'taro-icons';
import './index.scss';

// 星级评价类型定义
interface StarRating {
  id: number;
  studentName: string;
  studentAvatar: string;
  rating: number;
  content: string;
  images: string[];
  date: string;
  replied: boolean;
  replyContent?: string;
  replyDate?: string;
}

const StarManagementPage: React.FC = () => {
  const [ratings, setRatings] = useState<StarRating[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [selectedRating, setSelectedRating] = useState<StarRating | null>(null);
  const [showReplyModal, setShowReplyModal] = useState(false);
  const [replyContent, setReplyContent] = useState('');

  useEffect(() => {
    // 设置页面标题
    Taro.setNavigationBarTitle({ title: '星级管理' });
    // 加载星级评价数据
    loadRatingData();
  }, []);

  const loadRatingData = async () => {
    try {
      setIsLoading(true);
      // 模拟API调用
      // const response = await getStarRatingsApi();
      
      // 模拟数据
      const mockRatings: StarRating[] = [
        {
          id: 1,
          studentName: '张三',
          studentAvatar: 'https://via.placeholder.com/80',
          rating: 5,
          content: '教练教学认真负责，讲解细致，通过率高，强烈推荐！',
          images: [
            'https://via.placeholder.com/200x200',
            'https://via.placeholder.com/200x200'
          ],
          date: '2024-01-15 10:30',
          replied: true,
          replyContent: '感谢您的肯定，我会继续努力做好教学工作！',
          replyDate: '2024-01-15 11:00'
        },
        {
          id: 2,
          studentName: '李四',
          studentAvatar: 'https://via.placeholder.com/80',
          rating: 4,
          content: '教练技术很好，耐心指导，就是场地有点远。',
          images: [],
          date: '2024-01-14 15:20',
          replied: false
        },
        {
          id: 3,
          studentName: '王五',
          studentAvatar: 'https://via.placeholder.com/80',
          rating: 5,
          content: '一次通过考试，非常感谢教练的专业指导！',
          images: [
            'https://via.placeholder.com/200x200'
          ],
          date: '2024-01-13 09:15',
          replied: true,
          replyContent: '恭喜您通过考试！这是您努力练习的成果。',
          replyDate: '2024-01-13 10:00'
        },
        {
          id: 4,
          studentName: '赵六',
          studentAvatar: 'https://via.placeholder.com/80',
          rating: 3,
          content: '教练水平不错，但有时教学进度太快，希望能更耐心些。',
          images: [],
          date: '2024-01-10 14:45',
          replied: false
        }
      ];
      
      setRatings(mockRatings);
    } catch (error) {
      console.error('加载星级评价失败:', error);
      Taro.showToast({
        title: '数据加载失败，请重试',
        icon: 'none'
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleReply = (rating: StarRating) => {
    setSelectedRating(rating);
    setReplyContent('');
    setShowReplyModal(true);
  };

  const handleSubmitReply = async () => {
    if (!selectedRating || !replyContent.trim()) {
      Taro.showToast({
        title: '请输入回复内容',
        icon: 'none'
      });
      return;
    }

    try {
      Taro.showLoading({ title: '提交中...' });
      // 模拟提交回复
      // const response = await submitReplyApi(selectedRating.id, replyContent);
      
      setTimeout(() => {
        Taro.hideLoading();
        
        // 更新本地数据
        const updatedRatings = ratings.map(rating => 
          rating.id === selectedRating.id 
            ? { 
                ...rating, 
                replied: true,
                replyContent: replyContent.trim(),
                replyDate: new Date().toLocaleString('zh-CN')
              }
            : rating
        );
        setRatings(updatedRatings);
        
        setShowReplyModal(false);
        Taro.showToast({
          title: '回复成功',
          icon: 'success'
        });
      }, 1000);
    } catch (error) {
      console.error('提交回复失败:', error);
      Taro.hideLoading();
      Taro.showToast({
        title: '回复失败，请重试',
        icon: 'none'
      });
    }
  };

  const renderStars = (rating: number) => {
    const stars = [];
    for (let i = 1; i <= 5; i++) {
      stars.push(
        <MaterialIcons 
          key={i}
          name={i <= rating ? 'star' : 'star-border'}
          size={24}
          color="#ffb400"
        />
      );
    }
    return stars;
  };

  return (
    <View className="star-management-page">
      {isLoading ? (
        <View className="loading-container">
          <Text>加载中...</Text>
        </View>
      ) : (
        <ScrollView className="rating-scroll">
          {ratings.length > 0 ? (
            ratings.map(rating => (
              <View key={rating.id} className="rating-item">
                {/* 评价头部信息 */}
                <View className="rating-header">
                  <Image 
                    className="student-avatar" 
                    src={rating.studentAvatar} 
                    mode="aspectFill"
                  />
                  <View className="student-info">
                    <View className="student-name-row">
                      <Text className="student-name">{rating.studentName}</Text>
                      <View className="rating-stars">
                        {renderStars(rating.rating)}
                      </View>
                    </View>
                    <Text className="rating-date">{rating.date}</Text>
                  </View>
                  {!rating.replied && (
                    <TouchableOpacity 
                      className="reply-btn"
                      onPress={() => handleReply(rating)}
                    >
                      <Text className="reply-btn-text">回复</Text>
                    </TouchableOpacity>
                  )}
                </View>

                {/* 评价内容 */}
                <Text className="rating-content">{rating.content}</Text>

                {/* 评价图片 */}
                {rating.images.length > 0 && (
                  <View className="rating-images">
                    {rating.images.map((image, index) => (
                      <TouchableOpacity 
                        key={index}
                        className="rating-image"
                        onPress={() => {
                          Taro.previewImage({
                            urls: rating.images,
                            current: image
                          });
                        }}
                      >
                        <Image 
                          src={image} 
                          mode="aspectFill"
                        />
                      </TouchableOpacity>
                    ))}
                  </View>
                )}

                {/* 教练回复 */}
                {rating.replied && rating.replyContent && (
                  <View className="coach-reply">
                    <View className="reply-header">
                      <Text className="reply-label">教练回复：</Text>
                      <Text className="reply-date">{rating.replyDate}</Text>
                    </View>
                    <Text className="reply-content">{rating.replyContent}</Text>
                  </View>
                )}
              </View>
            ))
          ) : (
            <View className="empty-container">
              <MaterialIcons name="star-border" size={80} color="#ccc" />
              <Text className="empty-text">暂无星级评价</Text>
            </View>
          )}
        </ScrollView>
      )}

      {/* 回复弹窗 */}
      {showReplyModal && (
        <View className="modal-overlay">
          <View className="modal-content">
            <View className="modal-header">
              <Text className="modal-title">回复评价</Text>
              <TouchableOpacity onPress={() => setShowReplyModal(false)}>
                <MaterialIcons name="close" size={28} color="#666" />
              </TouchableOpacity>
            </View>
            
            <View className="reply-form">
              <Text className="reply-to">回复给：{selectedRating?.studentName}</Text>
              <Text className="original-rating">原评价：{selectedRating?.content}</Text>
              <textarea
                className="reply-input"
                placeholder="请输入回复内容"
                value={replyContent}
                onChange={(e) => setReplyContent(e.target.value)}
                rows={5}
              />
              <View className="modal-actions">
                <TouchableOpacity 
                  className="cancel-btn"
                  onPress={() => setShowReplyModal(false)}
                >
                  <Text className="cancel-btn-text">取消</Text>
                </TouchableOpacity>
                <TouchableOpacity 
                  className="submit-btn"
                  onPress={handleSubmitReply}
                >
                  <Text className="submit-btn-text">提交回复</Text>
                </TouchableOpacity>
              </View>
            </View>
          </View>
        </View>
      )}
    </View>
  );
};

export default StarManagementPage;